package com.example.musicapp.model;

import android.os.Looper;
import android.widget.Toast;

import com.example.musicapp.application.MyApp;
import com.example.musicapp.contract.IRegisterContract;
import com.example.musicapp.network.HttpResponseListener;
import com.example.musicapp.utils.HttpUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;

import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterModel implements IRegisterContract.IRegisterModel {
    @Override
    public void register(String username, String password, HttpResponseListener callBack) {

    }

    @Override
    public void sendMessage(String phone, HttpResponseListener callBack) {

        String url = "http://music.gochiusa.top" + "/captcha/sent";
        RequestBody body = new FormBody.Builder().add("phone", phone).build();
        HttpUtils.sendPostOkRequest(url, body, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败了");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                assert response.body() != null;
                String responseData = response.body().string();
                if (callBack != null) {
                    try {
                        callBack.onSuccess(responseData);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public void checkCode(String phone, String password, String code, String name, HttpResponseListener callBack) {
        String url = "http://music.gochiusa.top" + "/register/cellphone";
        RequestBody body = new FormBody.Builder().add("phone", phone).add("captcha", code).add("password", password).add("nickname", name).build();
        HttpUtils.sendPostOkRequest(url, body, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Looper.prepare();
                Toast.makeText(MyApp.getContext(),"很抱歉，注册失败", Toast.LENGTH_LONG).show();
                Looper.loop();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    assert response.body() != null;
                    callBack.onSuccess(response.body().string());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }


}
